#coding=utf-8
#Boa:FramePanel:PanelAccountDetail

import wx

from product import *
from ctrlAider import *
from MyListCtrl import MyAccountDetailListCtrl,MyListCtrlAccountDetailReport

import dbmngr
import kit

[wxID_PANELACCOUNTDETAIL, wxID_PANELACCOUNTDETAILBTNADDACCOUNT, 
 wxID_PANELACCOUNTDETAILBTNALLACCOUNT, wxID_PANELACCOUNTDETAILBTNALLDATE, 
 wxID_PANELACCOUNTDETAILBTNCLOSE, wxID_PANELACCOUNTDETAILBTNDEL, 
 wxID_PANELACCOUNTDETAILBTNLOAD, wxID_PANELACCOUNTDETAILBTNONEDAY, 
 wxID_PANELACCOUNTDETAILBTNONEMONTH, wxID_PANELACCOUNTDETAILBTNONEWEEK, 
 wxID_PANELACCOUNTDETAILBTNONEYEAR, wxID_PANELACCOUNTDETAILBTNSEARCH, 
 wxID_PANELACCOUNTDETAILBTNSHOWDETAIL, wxID_PANELACCOUNTDETAILBTNSHOWVOUCHER, 
 wxID_PANELACCOUNTDETAILCBACCOUNT, wxID_PANELACCOUNTDETAILDATEEND, 
 wxID_PANELACCOUNTDETAILDATESTART, wxID_PANELACCOUNTDETAILSTATICTEXT1, 
 wxID_PANELACCOUNTDETAILTACCOUNT, wxID_PANELACCOUNTDETAILTCSEARCH, 
 wxID_PANELACCOUNTDETAILTDATE, 
] = [wx.NewId() for _init_ctrls in range(21)]

class PanelAccountDetail(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELACCOUNTDETAIL,
              name=u'PanelAccountDetail', parent=prnt, pos=wx.Point(342, 109),
              size=wx.Size(929, 663), style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(913, 625))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False, u'Arial'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.tAccount = wx.StaticText(id=wxID_PANELACCOUNTDETAILTACCOUNT,
              label=u'\u9009\u62e9\u8d26\u6237\uff1a', name=u'tAccount',
              parent=self, pos=wx.Point(8, 64), size=wx.Size(88, 16), style=0)

        self.cbAccount = wx.ComboBox(choices=[],
              id=wxID_PANELACCOUNTDETAILCBACCOUNT, name=u'cbAccount',
              parent=self, pos=wx.Point(96, 56), size=wx.Size(168, 27),
              style=0, value=u'')
        self.cbAccount.SetLabel(u'')
        self.cbAccount.SetStringSelection(u'')
        self.cbAccount.Bind(wx.EVT_COMBOBOX, self.OnCbAccountCombobox,
              id=wxID_PANELACCOUNTDETAILCBACCOUNT)

        self.btnLoad = wx.Button(id=wxID_PANELACCOUNTDETAILBTNLOAD,
              label=u'\u5bfc\u5165xls\u660e\u7ec6', name=u'btnLoad',
              parent=self, pos=wx.Point(448, 56), size=wx.Size(120, 29),
              style=0)
        self.btnLoad.SetToolTipString(u'\xe5\xaf\xbc\xe5\x85\xa5excel\xe6\x96\x87\xe4\xbb\xb6\xef\xbc\x8c\xe8\xa6\x81\xe6\xb1\x82\xe5\xaf\xbc\xe5\x85\xa5\xe7\x9a\x84\xe6\x95\xb0\xe6\x8d\xae\xe5\xad\x98\xe5\x82\xa8\xe5\x9c\xa8\xe7\xac\xac\xe4\xb8\x80\xe4\xb8\xaasheet\xe4\xb8\xad\n\xe5\x86\x85\xe5\xae\xb9\xe6\xa0\xbc\xe5\xbc\x8f\xe8\xa6\x81\xe6\xb1\x82(\xe5\x9b\x9b\xe5\x88\x97)\xef\xbc\x9a\n    --\xe6\x97\xa5\xe6\x9c\x9f(\xe5\xa6\x822014-01-01)\n    --\xe6\x94\xb6\xe5\x85\xa5\n    --\xe6\x94\xaf\xe5\x87\xba\n    --\xe5\xa4\x87\xe6\xb3\xa8')
        self.btnLoad.Bind(wx.EVT_BUTTON, self.OnBtnLoadButton,
              id=wxID_PANELACCOUNTDETAILBTNLOAD)

        self.btnShowDetail = wx.Button(id=wxID_PANELACCOUNTDETAILBTNSHOWDETAIL,
              label=u'\u67e5\u8be2\u8d26\u6237\u53d8\u52a8\u660e\u7ec6',
              name=u'btnShowDetail', parent=self, pos=wx.Point(280, 56),
              size=wx.Size(152, 29), style=0)
        self.btnShowDetail.Bind(wx.EVT_BUTTON, self.OnBtnShowDetailButton,
              id=wxID_PANELACCOUNTDETAILBTNSHOWDETAIL)

        self.btnAddAccount = wx.Button(id=wxID_PANELACCOUNTDETAILBTNADDACCOUNT,
              label=u'\u65b0\u589e\u8d44\u91d1\u8d26\u6237',
              name=u'btnAddAccount', parent=self, pos=wx.Point(8, 96),
              size=wx.Size(120, 29), style=0)
        self.btnAddAccount.Bind(wx.EVT_BUTTON, self.OnBtnAddAccountButton,
              id=wxID_PANELACCOUNTDETAILBTNADDACCOUNT)

        self.btnDel = wx.Button(id=wxID_PANELACCOUNTDETAILBTNDEL,
              label=u'\u5220\u9664\u9009\u4e2d\u5217\u8868\u9879',
              name=u'btnDel', parent=self, pos=wx.Point(136, 96),
              size=wx.Size(136, 29), style=0)
        self.btnDel.Bind(wx.EVT_BUTTON, self.OnBtnDelButton,
              id=wxID_PANELACCOUNTDETAILBTNDEL)

        self.TDate = wx.StaticText(id=wxID_PANELACCOUNTDETAILTDATE,
              label=u'\u67e5\u8be2\u65e5\u671f\uff1a', name=u'TDate',
              parent=self, pos=wx.Point(8, 24), size=wx.Size(85, 19), style=0)
        self.TDate.SetAutoLayout(True)
        self.TDate.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'Arial'))

        self.dateStart = wx.DatePickerCtrl(id=wxID_PANELACCOUNTDETAILDATESTART,
              name=u'dateStart', parent=self, pos=wx.Point(96, 16),
              size=wx.Size(118, 27), style=wx.DP_DROPDOWN)
        self.dateStart.SetLabel(u'2014-04-24')
        self.dateStart.SetValue(wx.DateTimeFromDMY(24, 3, 2014, 0, 0, 0))
        self.dateStart.SetToolTipString(u'dateStart')

        self.staticText1 = wx.StaticText(id=wxID_PANELACCOUNTDETAILSTATICTEXT1,
              label=u'\u81f3', name='staticText1', parent=self,
              pos=wx.Point(222, 24), size=wx.Size(18, 18), style=0)

        self.dateEnd = wx.DatePickerCtrl(id=wxID_PANELACCOUNTDETAILDATEEND,
              name=u'dateEnd', parent=self, pos=wx.Point(254, 16),
              size=wx.Size(116, 27), style=wx.DP_DROPDOWN)

        self.btnOneDay = wx.Button(id=wxID_PANELACCOUNTDETAILBTNONEDAY,
              label=u'\u5f53\u65e5', name=u'btnOneDay', parent=self,
              pos=wx.Point(386, 16), size=wx.Size(46, 29), style=0)
        self.btnOneDay.Bind(wx.EVT_BUTTON, self.OnBtnOneDayButton,
              id=wxID_PANELACCOUNTDETAILBTNONEDAY)

        self.btnOneWeek = wx.Button(id=wxID_PANELACCOUNTDETAILBTNONEWEEK,
              label=u'\u4e00\u5468', name=u'btnOneWeek', parent=self,
              pos=wx.Point(434, 16), size=wx.Size(46, 29), style=0)
        self.btnOneWeek.Bind(wx.EVT_BUTTON, self.OnBtnOneWeekButton,
              id=wxID_PANELACCOUNTDETAILBTNONEWEEK)

        self.btnOneMonth = wx.Button(id=wxID_PANELACCOUNTDETAILBTNONEMONTH,
              label=u'\u4e00\u6708', name=u'btnOneMonth', parent=self,
              pos=wx.Point(482, 16), size=wx.Size(46, 29), style=0)
        self.btnOneMonth.Bind(wx.EVT_BUTTON, self.OnBtnOneMonthButton,
              id=wxID_PANELACCOUNTDETAILBTNONEMONTH)

        self.btnOneYear = wx.Button(id=wxID_PANELACCOUNTDETAILBTNONEYEAR,
              label=u'\u4e00\u5e74', name=u'btnOneYear', parent=self,
              pos=wx.Point(530, 16), size=wx.Size(46, 29), style=0)
        self.btnOneYear.Bind(wx.EVT_BUTTON, self.OnBtnOneYearButton,
              id=wxID_PANELACCOUNTDETAILBTNONEYEAR)

        self.btnAllDate = wx.Button(id=wxID_PANELACCOUNTDETAILBTNALLDATE,
              label=u'\u5168\u90e8', name=u'btnAllDate', parent=self,
              pos=wx.Point(578, 16), size=wx.Size(46, 29), style=0)
        self.btnAllDate.Bind(wx.EVT_BUTTON, self.OnBtnAllDateButton,
              id=wxID_PANELACCOUNTDETAILBTNALLDATE)

        self.btnClose = wx.Button(id=wxID_PANELACCOUNTDETAILBTNCLOSE,
              label=u'\u5173\u95ed', name=u'btnClose', parent=self,
              pos=wx.Point(744, 96), size=wx.Size(86, 29), style=0)
        self.btnClose.Bind(wx.EVT_BUTTON, self.OnBtnCloseButton,
              id=wxID_PANELACCOUNTDETAILBTNCLOSE)

        self.tcSearch = wx.TextCtrl(id=wxID_PANELACCOUNTDETAILTCSEARCH,
              name=u'tcSearch', parent=self, pos=wx.Point(280, 96),
              size=wx.Size(136, 28), style=0, value=u'')

        self.btnSearch = wx.Button(id=wxID_PANELACCOUNTDETAILBTNSEARCH,
              label=u'\u641c\u7d22', name=u'btnSearch', parent=self,
              pos=wx.Point(424, 96), size=wx.Size(56, 29), style=0)
        self.btnSearch.Bind(wx.EVT_BUTTON, self.OnBtnSearchButton,
              id=wxID_PANELACCOUNTDETAILBTNSEARCH)

        self.btnAllAccount = wx.Button(id=wxID_PANELACCOUNTDETAILBTNALLACCOUNT,
              label=u'\u67e5\u8be2\u6240\u6709\u8d26\u6237',
              name=u'btnAllAccount', parent=self, pos=wx.Point(584, 56),
              size=wx.Size(120, 29), style=0)
        self.btnAllAccount.Bind(wx.EVT_BUTTON, self.OnBtnAllAccountButton,
              id=wxID_PANELACCOUNTDETAILBTNALLACCOUNT)

        self.btnShowVoucher = wx.Button(id=wxID_PANELACCOUNTDETAILBTNSHOWVOUCHER,
              label=u'\u67e5\u770b\u8d26\u6237\u660e\u7ec6',
              name=u'btnShowVoucher', parent=self, pos=wx.Point(616, 96),
              size=wx.Size(118, 29), style=0)
        self.btnShowVoucher.Bind(wx.EVT_BUTTON, self.OnBtnShowVoucherButton,
              id=wxID_PANELACCOUNTDETAILBTNSHOWVOUCHER)

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.myInit()

    def myInit(self):
        tip = u'导入excel文件，要求导入的数据存储在第一个sheet中\n'
        tip += u'内容格式要求(五列)：\n'
        tip += u'    --日期(要求：2014-01-01或20140101或excel日期格式)\n'
        tip += u'    --收入(要求：\\或/或空)\n'
        tip += u'    --支出(要求：\\或/或空)\n'
        tip += u'    --用项\n'
        tip += u'    --备注\n'
        self.btnLoad.SetToolTipString(tip)
        
        self.dateStart.SetValue(wx.DateTime.Today())
        self.dateEnd.SetValue(wx.DateTime.Today())
        
        self.cb = MyComboBoxDecorator(self.cbAccount, CDataAccount, CDataAccount.COL_BRIEFNAME)
        self.cb.refresh()
        self.curAccount = None
        
        self.lc1 = MyListCtrlAccountDetailReport(self)
        self.lc1.SetSize(wx.Size(1200, 455))
        self.lc1.Move(wx.Point(10,130))

        self.lc2 = MyAccountDetailListCtrl(self)
        self.lc2.SetSize(wx.Size(1200, 455))
        self.lc2.Move(wx.Point(10,130))

        self.lc = self.lc1
        self.lc2.Show(False)

    def loadExcel(self, file):
        import xlrd
        import datetime
        
        if(self.curAccount is None):
            dlg = wx.MessageDialog(self, u'请先选择资金账户',u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return

        dataList = []
        # 注意日期格式一致才能比较, wx.DateTime,datetime.datetime,datetime.date
        #minDate = wx.DateTime.Today() 
        minDate = datetime.datetime.today()
        
        try:
            data = xlrd.open_workbook(file)
            table = data.sheet_by_index(0) # .sheets()[0] or .sheet_by_name(u'Sheet1')
            for i in range(table.nrows):
                list = table.row_values(i) + ['','','',''] #避免数据不足4列
                print list
                date,income,expend,useage,memo = list[:5]
                #date = date[:4] + '-' + date[4:6] + '-' + date[6:]
                #print table.row_values(i)
                #print type(date)
##                if (isinstance(date, str) or isinstance(date, unicode)):
##                    if (date.find('-') < 0):
##                        date = date[:4] + '-' + date[4:6] + '-' + date[6:]
##                elif (isinstance(date, float)):
##                    if(date > 20100101.0 and date < 20150101.0):
##                        date = '%.f' %date # %.g不行，会变成科学计数法
##                        print date
##                        date = date[:4] + '-' + date[4:6] + '-' + date[6:]
##                    else:
##                        date = xlrd.xldate.xldate_as_datetime(date, 0)
    
                if (isinstance(date, float)):
                    if(date < 20100101.0 or date > 20150101.0):
                        date = xlrd.xldate.xldate_as_datetime(date, 0)
                    else:
                        date = '%.f' %date # %.g不行，会变成科学计数法
                
                if (isinstance(date, str) or isinstance(date, unicode)):
                    date = date.strip() #直接从页面copy会产生空格
                    if (date.find('-') < 0):
                        date = datetime.datetime.strptime(date, "%Y%m%d")
                    else:
                        date = datetime.datetime.strptime(date, "%Y-%m-%d")

                sysmemo = u'【导入自%s】' %(file)
                dataList.append((date,income,expend,memo,sysmemo,useage))
                #print type(minDate),minDate
                #print type(date),date
                if minDate > date:
                    minDate = date
                    
        except Exception,e:
            print e
            return -1
        
        accountId = self.curAccount.getValue(CDataAccount.COL_ID)
        dbDate = CDataAccountDetail.getMaxDate(accountId)
        if dbDate is not None and minDate.date() < dbDate:
            msg = u'导入数据最小日期%s小于数据库中已有数据的最大日期%s\n'\
                    u'出现数据交叉，是否继续导入？' %(minDate, dbDate)
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if dlg.ShowModal() == wx.ID_NO:
                return -1
        
        #msg = '%s' %dataList
        #dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
        #if dlg.ShowModal() == wx.ID_NO:
        #    return -1
        
        try:
            dbmngr.dbmngr.beginTrans()
            
            loadTime = datetime.datetime.now()
            for date,income,expend,memo,sysmemo,useage in dataList:
                obj = CDataAccountDetail.factory()
                # 140711
                #obj.assignNewId()
                obj.setValue(CDataAccountDetail.COL_ACCOUNTID, accountId)
                obj.setValue(CDataAccountDetail.COL_DATE, date)
                if (income != '' and income != '/' and income != '\\'):
                    money = float(income)
                elif (expend != '' and expend != '/' and expend != '\\'):
                    money = -float(expend)
                else:
                    msg = u'以下数据存在问题，现在跳过改行，请稍后仔细查看：\n%s,%s,%s,%s' %(date,income,expend,memo)
                    dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
                    dlg.ShowModal()
                    continue
                
                obj.setValue(CDataAccountDetail.COL_MONEY, money)
                #obj.setValue(CDataAccountDetail.COL_REMAIN, float(remain))
                #obj.setValue(CDataAccountDetail.COL_FUNDID, )
                obj.setValue(CDataAccountDetail.COL_MEMO, memo)
                obj.setValue(CDataAccountDetail.COL_SYSMEMO, sysmemo)
                obj.setValue(CDataAccountDetail.COL_TIME, loadTime)
                obj.setValue(CDataAccountDetail.COL_USEAGE, useage)
                obj.setValue(CDataAccountDetail.COL_LOADIN,1)
                obj.insert()
        
            dbmngr.dbmngr.commitTrans()
        except Exception as e:
            dbmngr.dbmngr.rollbackTrans(e)
            return -1
            
        return 0
     
    def refresh(self):
        
        filter = {
            'dateStart':self.dateStart.GetValue().Format('%Y-%m-%d'),
            'dateEnd':self.dateEnd.GetValue().Format('%Y-%m-%d'),
        }
        
        self.curAccount = self.cb.getSelectObj()
        if self.curAccount is not None:
            filter['accountId'] = self.curAccount.getValue(CDataAccount.COL_ID)
                    
        self.lc.refresh(filter)
    
    def getAccountObj(self):
        return self.curAccount
    
    def OnCbAccountCombobox(self, event):
        #print self.cb.GetValue()
        self.curAccount = self.cb.getSelectObj()
        
    def OnBtnLoadButton(self, event):
        if(self.curAccount is None):
            dlg = wx.MessageDialog(self, u'请先选择资金账户',u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
            
        dlg = wx.FileDialog(self)
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return
        
        file = dlg.GetPath()
        
        msg = u'请确认以下信息，以便导入数据：\n'
        msg += u'    导入账户：%s \n' %self.curAccount.getValue(self.curAccount.COL_BRIEFNAME)
        msg += u'    导入文件：%s' %file
        dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_INFORMATION)
        if(dlg.ShowModal() == wx.ID_NO):
            return
    
        if(self.loadExcel(file) == 0):
            msg = u'导入文件成功'
        else:
            msg = u'导入文件失败，请检查文件格式是否正确'
            
        dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        
        self.refresh()

    def OnBtnShowDetailButton(self, event):
        # if(self.curAccount is None):
            # dlg = wx.MessageDialog(self, u'请先选择资金账户',u'提示',wx.OK|wx.ICON_INFORMATION)
            # dlg.ShowModal()
            # return
            
                    
        self.refresh()

    def OnBtnAddAccountButton(self, event):
        import DlgAccountEditor
        dlg = DlgAccountEditor.create(self)
        if(dlg.ShowModal() == wx.ID_CANCEL):
            return
        
        self.cb.refresh()
        
        self.curAccount = dlg.getObj()
        if(self.curAccount is not None):
            self.cb.SetValue(self.curAccount.getValue(self.curAccount.COL_BRIEFNAME))        
            self.refresh()
        
    def OnBtnDelButton(self, event):
        if (self.lc.GetSelectedItemCount() <= 0):
            msg = u'请首先选择列表项目'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
            
        msg = u'删除后将无法恢复，是否确认删除？'
        dlg = wx.MessageDialog(self, msg, u'提示',wx.YES_NO|wx.ICON_INFORMATION)
        if(dlg.ShowModal() == wx.ID_NO):
            return
        
        self.lc.deleteSelection()

    def OnBtnOneDayButton(self, event):
        self.dateStart.SetValue(wx.DateTime.Today())
        self.dateEnd.SetValue(wx.DateTime.Today())

    def OnBtnOneWeekButton(self, event):
        day = wx.DateTime.Today()
        self.dateEnd.SetValue(day)
        
        span = wx.DateSpan.Days(7)
        day.SubtractDS(span)
        self.dateStart.SetValue(day)

    def OnBtnOneMonthButton(self, event):
        day = wx.DateTime.Today()
        self.dateEnd.SetValue(day)
        
        span = wx.DateSpan.Months(1)
        day.SubtractDS(span)
        self.dateStart.SetValue(day)

    def OnBtnOneYearButton(self, event):
        day = wx.DateTime.Today()
        self.dateEnd.SetValue(day)
        
        span = wx.DateSpan.Years(1)
        day.SubtractDS(span)
        self.dateStart.SetValue(day)

    def OnBtnAllDateButton(self, event):
        self.dateEnd.SetValue(wx.DateTime.Today())        
        self.dateStart.SetValue(wx.DateTimeFromDMY(1,0,2000,0,0,00))

    def doClose(self, doQuit=True):
        if doQuit:
            book = self.GetParent()
            book.DeletePage(book.GetSelection())
        return True
        
    def OnBtnCloseButton(self, event):
        self.doClose()

    def OnBtnSearchButton(self, event):
        val = self.tcSearch.GetValue()
        if not val:
            return
        
        self.lc.refreshView(val)

    def OnBtnAllAccountButton(self, event):
        # filter = {'dateStart':self.dateStart.GetValue().Format('%Y-%m-%d'),
        #             'dateEnd':self.dateEnd.GetValue().Format('%Y-%m-%d')}
                    
        # self.lc.refresh(filter)

        self.refresh()

    def OnBtnShowVoucherButton(self, event):
        self.lc = self.lc2
        self.lc1.Show(False)
        self.lc.Show(True)
        self.refresh()
